package com.likou.second_challenge;

public class q25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode ans = new ListNode(0, head);
        ListNode p1 = head;

        int n = 0;
        while (p1 != null) {
            n++;
            p1 = p1.next;
        }

        ListNode p2 = ans;
        while (n >= k) {
            ListNode p3 = p2.next;
            ListNode p4 = null;
            ListNode p5 = p2.next;
            for (int i = 0; i < k; i++) {
                ListNode temp = p5.next;
                p5.next = p4;

                p4 = p5;
                p5 = temp;
            }

            p3.next = p5;
            p2.next = p4;
            p2 = p3;
            n -= k;
        }

        return ans.next;
    }
}
